package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"store-master/models"
)

type StoreController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (s *StoreController) Add() {

	img := s.GetString("img")
	name := s.GetString("name")
	address := s.GetString("address")
	status := s.GetString("status")
	store := models.Store{
		Img:     img,
		Name:    name,
		Address: address,
		Status:  status,
	}
	err := models.DB.Create(&store).Error
	if err != nil {
		s.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
		}
		s.ServeJSON()
		return
	} else {
		s.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
		}
		s.ServeJSON()
	}

}
func (s *StoreController) Upload() {

	file, head, err := s.GetFile("img")
	if err != nil {
		s.Data["json"] = Res{
			Code: 0,
			Msg:  "文件获取失败",
		}
		s.ServeJSON()
		return
	}
	if head.Size > 2*1024*1024 {
		s.Data["json"] = Res{
			Code: 0,
			Msg:  "文件过大",
		}
		s.ServeJSON()
		return
	}
	defer file.Close()
	path := "static/img" + head.Filename
	err = s.SaveToFile("img", path)
	if err != nil {
		s.Data["json"] = Res{
			Code: 0,
			Msg:  "文件上传失败",
		}
		s.ServeJSON()
		return
	} else {
		Url := "http://127.0.0.1:8080/" + path
		s.Data["json"] = Res{
			Code: 200,
			Msg:  "文件上传成功",
			Data: Url,
		}
		s.ServeJSON()
	}
}
func (s *StoreController) Update() {

	id, _ := s.GetInt("id")
	img := s.GetString("img")
	name := s.GetString("name")
	address := s.GetString("address")
	status := s.GetString("status")
	store := models.Store{
		Img:     img,
		Name:    name,
		Address: address,
		Status:  status,
	}
	err := models.DB.Where("id=?", id).Updates(store).Error
	if err != nil {
		s.Data["json"] = Res{
			Code: 0,
			Msg:  "修改失败",
		}
		s.ServeJSON()
		return
	} else {
		s.Data["json"] = Res{
			Code: 200,
			Msg:  "修改成功",
		}
		s.ServeJSON()
	}

}
func (s *StoreController) List() {

	page, _ := s.GetInt("page", 1)
	size, _ := s.GetInt("size", 3)
	offset := (page - 1) * size
	query := models.DB.Model(&models.Store{})
	var count int64
	query.Count(&count)
	var store []models.Store
	err := query.Offset(offset).Limit(size).Find(&store).Error
	if err != nil {
		s.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
		}
		s.ServeJSON()
		return
	} else {
		PageData := make(map[string]interface{})
		PageData["count"] = count
		PageData["store"] = store
		s.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: PageData,
		}
		s.ServeJSON()
	}
}
